package club.hicode.daydayup.netty.udp.client2;

import club.hicode.daydayup.netty.udp.MessageBo;
import club.hicode.daydayup.netty.udp.client.AbstractReq;
import club.hicode.daydayup.netty.udp.client.UdpChannelInitializer;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.ThreadUtil;
import com.github.jsonzou.jmockdata.JMockData;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;

import java.util.concurrent.TimeUnit;

/**
 * UDP的Server
 *
 * @author Liu Chunfu
 * @date 2018-07-09 上午11:19
 **/
public class UdpClient2 {

    /**
     * 此处没有考虑失败的问题啊
     *
     * @throws Exception
     */
    public void run() throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        try {
            Channel channel = bootstrap.group(group).channel(NioDatagramChannel.class)
                    .option(ChannelOption.SO_BROADCAST, true)
                    .handler(new UdpChannelInitializer2()).bind(0)
                    .sync().channel();
            CommunicationContext.setChannel(channel);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //此处不可以优雅关机？
            //group.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        new Thread(() -> {
            try {
                new UdpClient2().run();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
        ThreadUtil.sleep(1, TimeUnit.SECONDS);
        Sendor sendor = new Sendor();
        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                MessageBo mock = JMockData.mock(MessageBo.class);
                SyncFuture<MessageBo> future = sendor.send(mock);
                MessageBo messageBo = null;
                try {
                    messageBo = future.get();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(DateUtil.now() + "收到了：" + messageBo);
            }).start();
        }
        ThreadUtil.sleep(4, TimeUnit.HOURS);
    }
}
